package class22;

/**
 * @author zhangchaoliang
 * create 2022
 */
public class ZigZagPrintMatrix {

    public static void printMatrixZigZag(int[][] matrix){
        int Ar = 0;
        int Ac = 0;
        int Br = 0;
        int Bc = 0;
        int Endr= matrix.length-1;
        int Endc = matrix[0].length-1;
        boolean fromUp = false;
        while (Ar != Endr + 1){
            printLevel(matrix,Ar,Ac,Br,Bc,fromUp);
            Ar = Ac==Endc? Ar+1:Ar;
            Ac = Ac==Endc?Ac:Ac+1;
            Bc = Br==Endr?Bc+1:Bc;
            Br = Br == Endr?Br:Br+1;
            fromUp = !fromUp;
        }
        System.out.println();
    }

    public static void printLevel(int[][] m,int tr,int tc,int dr,int dc,boolean f){
        if (f){
            while (tr != dr + 1) {
                System.out.print(m[tr++][tc--]+" ");
            }
        }else {
            while (dr != tr-1){
                System.out.print(m[dr--][dc++]+" ");
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
        printMatrixZigZag(matrix);
    }
}
